package br.com.async.agilequiz.dao;

import java.util.List;

import android.database.SQLException;
import br.com.async.agilequiz.database.DatabaseHelper;
import br.com.async.agilequiz.domain.Question;

import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;

public class QuestionDao {
	
	Dao<Question, Integer> questionDao;
	
	public QuestionDao(DatabaseHelper db){
		try {
			questionDao = db.getDao(Question.class);
		} catch (SQLException e) {
			// TODO: Exception Handling
			e.printStackTrace();
		} catch (java.sql.SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void create(Question question){
		try {
			questionDao.create(question);
			System.out.println("question created!");
		} catch (java.sql.SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void update(Question question){
		try {
			questionDao.update(question);
			System.out.println("question updated!");
		}catch (java.sql.SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void delete(Question question){
		try {
			questionDao.delete(question);
			System.out.println("question deleted!");
		}catch (java.sql.SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public Question getquestionById(Integer id){
		try{
			
			QueryBuilder<Question, Integer> qb = questionDao.queryBuilder();
			qb.where().eq("id",id);
			PreparedQuery<Question> pq = qb.prepare();
			return questionDao.queryForFirst(pq);
			
		}catch (java.sql.SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public Question getQuestionByName(String name){		
		try {
			QueryBuilder<Question, Integer> qb = questionDao.queryBuilder();
			
			//qb.where().eq("name", name);
			qb.where().like("name","%"+name+"%");
			
			PreparedQuery<Question> pq = qb.prepare();
			
			return questionDao.queryForFirst(pq);
		}catch (java.sql.SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	
	public List<Question> getAll(){		
		try {
			return questionDao.queryForAll();
		}catch (java.sql.SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}


}
